local httpclient     = require "shared.http.client"
local contenthelper  = require "shared.http-content-helper"
local config         = require "config"
local json           = require("shared.json")
local cjson          = require("cjson.safe")
      cjson.encode_max_depth(32)
      cjson.decode_max_depth(32)
local def            = require("shared.api.def")
local ERROR_CODE     = def.ERROR_CODE

local WALLET_SERVICE = config.ENV.WALLET_SERVICE

local JSON_OPT = {
  use_json_number = true,
}


local _M = { _VERSION = "0.1" }

local function _fill_response_header(headers)
  if type(headers) == 'table' then
    for k, v in pairs(headers) do
      if string.lower(k) == 'content-type' then
        ngx.header[k] = v
      end
    end
  end
end

local function _resolve_response(resp)
  if resp.status ~= 200 then
    if resp.status == 400 then
      if contenthelper.match_content_type(resp, 'application/json')  then
        local content = contenthelper.decode(resp.headers, resp.body)
        local err     = cjson.decode(content)
        return nil, err
      end
    end

    ngx.status = resp.status
    _fill_response_header(resp.headers)
    ngx.say(resp.body)
    ngx.exit(ngx.OK)
  end

  local content = contenthelper.decode(resp.headers, resp.body)
  return cjson.decode(content)
end


-- account
do
  local ACCOUNT = {}
  local ACCOUNT_PATH              = "/account"
  local ACCOUNT_RELOAD_BONUS_PATH = ACCOUNT_PATH.."/reload_bonus"


  function ACCOUNT.peek_reload_bonus(args)
    local data = cjson.encode(args)
    local resp, err = httpclient.new()
      :uri(WALLET_SERVICE..ACCOUNT_RELOAD_BONUS_PATH)
      :body(data)
      :send("PEEK", 2000, nil)

    if err or (not resp) then
      ngx.status = 500
      ngx.say(err)
      ngx.exit(ngx.OK)
    end

    return _resolve_response(resp)
  end


  function ACCOUNT.redeem_reload_bonus(args)
    local data = cjson.encode(args)
    local resp, err = httpclient.new()
      :uri(WALLET_SERVICE..ACCOUNT_RELOAD_BONUS_PATH)
      :body(data)
      :send("REDEEM", 2000, nil)

    if err or (not resp) then
      ngx.status = 500
      ngx.say(err)
      ngx.exit(ngx.OK)
    end

    return _resolve_response(resp)
  end

  -- export
  _M.account = ACCOUNT
end

return _M
